<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Admin\Models\storeGoodsOut;
use App\Admin\Models\Common;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Show;
use Encore\Admin\Facades\Admin;
use Illuminate\Support\MessageBag;
use Illuminate\Support\Facades\Input;
use Illuminate\Http\Request;
use Ixudra\Curl\Facades\Curl;
use Field\Interaction\FieldTriggerTrait;
use Field\Interaction\FieldSubscriberTrait;
use DB;

class StoreGoodsOutController extends Controller
{
	use HasResourceActions, FieldTriggerTrait, FieldSubscriberTrait;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('出库单')
            ->description('列表')
            ->body($this->grid());
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
    	$content->header('商品售出')->description(' ');

    	return $this->form($content);
        return $content
            ->header('商品出库')
            ->description('新增')
            ->body($this->form($content));

    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
    	$sId = Admin::user()->sId;
		$createUser = Admin::user()->name;

        $grid = new Grid(new StoreGoodsOut);
        $grid->sgoId('ID');
        $grid->sgiBatchCode('批次号');
        $grid->sgName('商品名称');
        $grid->sgoSalePrice('售出总价');
        $grid->sgoSaleNum('售出数量');
        $grid->sgoCost('成本');
        $grid->sgoProfit('利润');
		$grid->muNickName('购买会员');
		$grid->sgoPayWay('支付方式');
		$grid->createUser('记录人');
        $grid->createTime('记录时间');

		$grid->filter(function($filter){

		    // 去掉默认的id过滤器
		    $filter->disableIdFilter();

		});

		$grid->actions(function ($actions) {
			// 加载confirm的html
		    $actions->disableDelete();
		    $actions->disableEdit();
		    $actions->disableView();

		    if ($actions->row->sgoIsCancel == 0){
		    	// append一个操作
    			$actions->append('<button data-id="'.$actions->row->sgoId.'" type="button" class="btn btn-block btn-danger btn-xs btnChannel">取消订单</button>');
		    }else{
		    	$sgoId = $actions->row->sgoId;
		    	$actions->append('<lable class="font-size">已取消</lable>');
		    	$actions->append('<input type="hidden" id="sign'.$sgoId.'">');
		    	$grayScript = <<<EOT

	$('#sign{$sgoId}').parent().parent().css({"background": "#CCCCCC"});

EOT;
				Admin::script($grayScript);
		    }
		});

		//隐藏删除按钮
		$hideScript = <<<EOT

$('.btnChannel').unbind('click').click(function() {

    var id = $(this).data('id');

    swal({
        title: "确认取消该出库单?",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "确认",
        showLoaderOnConfirm: true,
        cancelButtonText: "取消",
        preConfirm: function() {
            return new Promise(function(resolve) {
                $.ajax({
                    method: 'post',
                    url: '../main/channelGoodsOut',
                    data: {
                        sgoId: id,
                        operator: "{$createUser}"
                    },
                    success: function (data) {
                    	console.log('success data:')
                    	console.log(data);

                        $.pjax.reload('#pjax-container');
                        resolve(data);

                        if (data.code == 1){
                        	location.reload();
                        }else{
                        	toastr.warning(data.msg);
                        }
                    },
                    fail: function (data) {
                    	console.log('fail data:')
                    	console.log(data)
                        $.pjax.reload('#pjax-container');
                        resolve(data);

                        toastr.warning('取消失败，请联系系统管理员');
                    }
                });
            });
        }
    }).then(function(result) {

    });
});

EOT;
			Admin::script($hideScript);

		$grid->filter(function($filter){

		    // 去掉默认的id过滤器
		    $filter->disableIdFilter();

		    $filter->column(1/2, function ($filter) {

		    	$filter->like('sgName', '商品名称');

			});

            $filter->column(1/2, function ($filter) {

            	$filter->like('muNickName', '购买会员');

            });

		});

//		// 默认展开筛选框
		$grid->expandFilter();

		// 禁用行选择checkbox
		$grid->disableRowSelector();

		// 禁用导出
		$grid->disableExport();
        return $grid;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form($content)
    {
    	$sId = Admin::user()->sId;
		$sgList = DB::table('store_goods')->where('sId', $sId)->get();
		$muList = DB::table('member_users')->where('mcId', $sId)->get();
        $bcList = DB::table('admin_users')
                            ->leftJoin('admin_role_users', 'admin_role_users.user_id', 'admin_users.id')
                            ->where('admin_role_users.role_id', 5)
                            ->where('admin_users.sId', $sId)
                            ->get();
		$createUser = Admin::user()->name;

		return $content->view('admin.goods.storeGoodsOut', ['sgList' => $sgList, 'muList' => $muList, 'bcList' => $bcList,
								'sId' => $sId, 'createUser' => $createUser]);
		exit;







        return Admin::Form(StoreGoodsOut::class, function (Form $form) {

			$sId = Admin::user()->sId;

			$form->hidden('sgiId');
			$StoreGoodsOut = new StoreGoodsOut();
			$productData = $StoreGoodsOut->getStoreGoodsList();
			$form->select('sgId', '商品')->options($productData);
			$form->text('sgUnitPrice', '商品单价')->readOnly();
			$form->select('muId', '购买会员')->options($this->getUserSelect());
			$form->text('alName', '会员身份')->readOnly();
			$form->text('sgMemberUnitPrice', '可享会员单价')->readOnly();
			$states = [
			    'on'  => ['value' => 1, 'text' => '是', 'color' => 'success'],
			    'off' => ['value' => 0, 'text' => '否', 'color' => 'danger'],
			];
			$form->switch('customUnitPriceSwich', '自定义售出单价')->states($states)->default(0);
			$form->text('customUnitPrice', '')->placeholder('请输入自定义单价');
			$form->text('sgoSaleNum', '购买数量')->default(1);
			$form->text('accountMoney', '会员卡余额')->readOnly()->help('系统会优先消费会员卡余额，支付方式为【会员卡】。如卡内余额不足，请选择另外的支付方式');
			$hideScript = <<<EOT

if ($('#accountMoney').val() <= 0){
	$('#accountMoney').parent().parent().parent().hide();
}
$('#sgUnitPrice').parent().parent().parent().hide();
$('#alName').parent().parent().parent().hide();
$('#sgMemberUnitPrice').parent().parent().parent().hide();
$('.customUnitPriceSwich').parent().parent().hide();
$('#customUnitPrice').parent().parent().parent().hide();
EOT;
			Admin::script($hideScript);
			$form->text('sgoSalePrice', '总支付')->default(0)->readOnly();
			$form->select('sgoPayWay', '支付方式')->options(['现金'=>'现金','支付宝'=>'支付宝','微信'=>'微信', '会员卡'=>'会员卡', '收钱吧'=>'收钱吧', '中国工商银行'=>'中国工商银行']);
			$form->text('sgoMemo', '备注');

			//////////////////////////////////////////////////////////////////////////////////////////////////
			// 弄一个触发事件的Script对象。
        	$trigger_script = $this->createTriggerScript($form);
        	// 添加事件响应事件
        	$subscriber_script = $this->createSubscriberScript($form, function($builder) use($sId) {

	            $builder->subscribe('sgId', 'select', function ($event) use($sId) {
	                $script = <<<EOT
	                	function (data){
	                		var uId = $('select[name="muId"]').val()
						    var sgId = $('select[name="sgId"]').val()

							var url = "../../main/getGoodsPrice?sId={$sId}&sgId="+sgId+"&muCode="+uId;

						    $.get(url, function (data) {
						    	data =JSON.parse(data);
						    	if (data.code == 0){
						    		//alert(data.msg);
						    		return;
						    	}

						    	if (uId){
						    		// 会员单价
							    	$('#sgMemberUnitPrice').parent().parent().parent().show();
							    	$('input[name="sgMemberUnitPrice"]').val(data.data.goodsPrice);
						    	}

						    	console.log(data.data);
						    	var sgoSaleNum = $('input[name="sgoSaleNum"]').val();
		                		sgoSaleNum = parseInt(sgoSaleNum);
								if (isNaN(sgoSaleNum)){
									$('input[name="sgoSaleNum"]').val('1');
						    		sgoSaleNum = 1;
						    	}
						    	console.log(sgoSaleNum);
						    	// 会员支付价
								$('input[name="sgoSalePrice"]').val(data.data.goodsPrice * sgoSaleNum);
						    });

						    // 获取商品单价
						    var sellPriceurl = "../../main/getGoodsPrice?sId={$sId}&sgId="+sgId+"&muCode=";

						    $.get(sellPriceurl, function (data) {
						    	data =JSON.parse(data);
						    	if (data.code == 0){
						    		//alert(data.msg);
						    		return;
						    	}

						    	console.log(data.data);
						    	$('input[name="sgUnitPrice"]').val(data.data.goodsPrice);
						    	$('#sgUnitPrice').parent().parent().parent().show();
						    });
	                	}
EOT;
					return $script;
	            });

	            // 监听sgiNum的input事件
	            $builder->subscribe('muId', 'select', function ($event) use($sId) {
	                $script = <<<EOT
	                	function (data){
	                		var uId = $('select[name="muId"]').val()
						    var sgId = $('select[name="sgId"]').val()

							// 获取会员产品价格
							var url = "../../main/getGoodsPrice?sId={$sId}&sgId="+sgId+"&muCode="+uId;

						    $.get(url, function (data) {
						    	data =JSON.parse(data);
						    	if (data.code == 0){
						    		//alert(data.msg);
						    		return;
						    	}
						    	// 会员单价
						    	$('#sgMemberUnitPrice').parent().parent().parent().show();
						    	$('input[name="sgMemberUnitPrice"]').val(data.data.goodsPrice);
						    	// 是否自定义
						    	$('.customUnitPriceSwich').parent().parent().show();

						    	console.log(data.data);
						    	var sgoSaleNum = $('input[name="sgoSaleNum"]').val();
		                		sgoSaleNum = parseInt(sgoSaleNum);
								if (isNaN(sgoSaleNum)){
									$('input[name="sgoSaleNum"]').val('1');
						    		sgoSaleNum = 1;
						    	}
						    	console.log(sgoSaleNum);
								$('input[name="sgoSalePrice"]').val(data.data.goodsPrice * sgoSaleNum);
						    });

						    if (!uId){
						    	return;
						    }

						    // 获取会员卡余额
						    var moneyUrl = "../../main/getAccountMoney?sId={$sId}&userCode="+uId;
						    $.get(moneyUrl, function (data) {
						    	data =JSON.parse(data);
						    	if (data.code == 0){
						    		//alert(data.msg);
						    		return;
						    	}
						    	console.log(data);
						    	$('#accountMoney').val(data.data)
						    	if (data.data == 0){
						    		$('#accountMoney').parent().parent().parent().hide();
						    	}else{
						    		$('#accountMoney').parent().parent().parent().show();
						    	}
						    });
	                	}
EOT;
					return $script;
	            });


	            $builder->subscribe('sgoSaleNum', 'input', function ($event) use($sId) {
	                $script = <<<EOT
	                	function (data){
	                		var customUnitPrice = $('input[name="customUnitPrice"]').val();
	                		customUnitPrice = Number(customUnitPrice);
							if (isNaN(customUnitPrice)){
								$('input[name="sgoSaleNum"]').val('0');
					    		customUnitPrice = 0;
					    	}
					    	if (customUnitPrice > 0){
					    		var sgoSaleNum = $('input[name="sgoSaleNum"]').val();
		                		sgoSaleNum = parseInt(sgoSaleNum);
								if (isNaN(sgoSaleNum)){
									$('input[name="sgoSaleNum"]').val('1');
						    		sgoSaleNum = 1;
						    	}
						    	$('input[name="sgoSalePrice"]').val(customUnitPrice * sgoSaleNum);
						    	return;
					    	}

	                		var uId = $('select[name="muId"]').val()
						    var sgId = $('select[name="sgId"]').val()

							var url = "../../main/getGoodsPrice?sId={$sId}&sgId="+sgId+"&muCode="+uId;

						    $.get(url, function (data) {
						    	data =JSON.parse(data);
						    	if (data.code == 0){
						    		//alert(data.msg);
						    		return;
						    	}
						    	console.log(data.data);
						    	var num = $('input[name="sgoSaleNum"]').val();
						    	if (!num){
						    		num = 1;
						    	}
						    	console.log(num);
								$('input[name="sgoSalePrice"]').val(data.data.goodsPrice*num);
						    });
	                	}
EOT;
					return $script;
	            });

	            $builder->subscribe('customUnitPrice', 'input', function ($event) use($sId) {
	                $script = <<<EOT
	                	function (data){
	                		var sgoSaleNum = $('input[name="sgoSaleNum"]').val();
	                		sgoSaleNum = parseInt(sgoSaleNum);
							if (isNaN(sgoSaleNum)){
								$('input[name="sgoSaleNum"]').val('1');
					    		sgoSaleNum = 1;
					    	}

							var customUnitPrice = $('input[name="customUnitPrice"]').val();
	                		customUnitPrice = Number(customUnitPrice);
							if (isNaN(customUnitPrice)){
								$('input[name="sgoSaleNum"]').val('0');
					    		customUnitPrice = 0;
					    	}

						    $('input[name="sgoSalePrice"]').val(customUnitPrice * sgoSaleNum);
	                	}
EOT;
					return $script;
	            });

	            $builder->subscribe('customUnitPriceSwich', 'switchchange', function ($event) use($sId) {
	                $script = <<<EOT
	                	function (data){
	                		console.log(data)
	                		if (data == 'on'){
	                			$('#customUnitPrice').parent().parent().parent().show();
	                		}else{
	                			$('#customUnitPrice').parent().parent().parent().hide();
	                			$('input[name="sgoSalePrice"]').val('');
	                		}
	                	}
EOT;
					return $script;
	            });
       		});

       		/* 将 trigger_script 和 subscriber_script 注入 form 中 */
        	$form->scriptinjecter('name_no_care', $trigger_script, $subscriber_script);
			//////////////////////////////////////////////////////////////////////////////////////////////////
			$common = $this->common;
			$form->saving(function (Form $form) use($sId, $common) {
			    $sgId = $form->sgId;
			    $sgInfo = DB::table('store_goods')->where('sgId', $sgId)->first();
			    // 判断是否为卡项
			    if (!$sgInfo->sgIsTimeCard){
			    	$muId = $form->muId;
				    if ($form->customUnitPrice){
				    	$sgoSalePrice = $form->customUnitPrice;
				    }else{
				    	$sgoSalePrice = $form->sgoSalePrice;
				    }
				    $sgoSaleNum = $form->sgoSaleNum;
	//			    print_r($sId.'|'.$muId.'|'.$sgId);exit
				    $minPrice = $common->getAmiBottomPrice($sId, $muId, $sgId);
				    if ($minPrice * $sgoSaleNum > $sgoSalePrice){
				    	$error = new MessageBag([
	//				        'title'   => $sId.'|'.$muId.'|'.$sgId,
							'title'   => '提交失败',
					        'message' => '该商品本次交易最低单价为：'.$minPrice.'元,总价不能低于：'.$minPrice * $sgoSaleNum.'元'
					    ]);

					    return back()->with(compact('error'))->withInput();
				    }
				    $form->minPrice = $minPrice;
			    }else{
			    	$form->minPrice = 0;
			    }
			});

            $form->tools(function (Form\Tools $tools) {

			    // 去掉`列表`按钮
//			    $tools->disableList();

			    // 去掉`删除`按钮
			    $tools->disableDelete();

			    // 去掉`查看`按钮
//			    $tools->disableView();

			    // 添加一个按钮, 参数可以是字符串, 或者实现了Renderable或Htmlable接口的对象实例
//			    $tools->add('<a class="btn btn-sm btn-danger"><i class="fa fa-trash"></i>&nbsp;&nbsp;delete</a>');
			});

			$form->footer(function ($footer) {

//			    // 去掉`重置`按钮
//			    $footer->disableReset();
//
//			    // 去掉`提交`按钮
//			    $footer->disableSubmit();

			    // 去掉`查看`checkbox
			    $footer->disableViewCheck();

			    // 去掉`继续编辑`checkbox
			    $footer->disableEditingCheck();

			    // 去掉`继续创建`checkbox
//			    $footer->disableCreatingCheck();

			});
        });
    }

    // 获取会员下拉框
    private function getUserSelect(){
    	$sId = Admin::user()->sId;
		$host = config('admin.dataApiHost');
		$url = $host.'/member/getList?mcKey='.$sId.'&page=1&perPage=999';

		$data = Curl::to($url)->get();

		$data = json_decode($data, true);
		$infoList = $data['data']['data'];

		$selectData = array();
		foreach($infoList as $info){
			$selectData[$info['muCode']] = $info['muNickName'];
		}

		return $selectData;
    }

}
